/*
 * UserThread.java
 *
 * Created on January 22, 2007, 12:08 AM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package ca.uvic.group2.testHarness;
import java.util.*;
import java.io.*;
import java.net.*;
import org.apache.log4j.*;

/**
 *
 * @author pat
 */
public class UserThread extends Thread{

    private static Category debugLog = Logger.getInstance("TestHarnessDebug");

    private String filename;
    private String sessionID;
    private int timeToQuit;
    private HashMap sessions = new HashMap();
    private String host;

    /** Creates a new instance of UserThread */
    public UserThread(String filename, int timeToQuit, String host) {
        super();
        this.filename = filename;
        this.timeToQuit = timeToQuit;
        this.host = host;
        debugLog.info("UserThread for " + filename + " created");
        //System.out.println("User thread created for host "+ host);
    }//endMethod

    public void run() {
        debugLog.info(filename + " started processing");
        String lineIn;
        long startTime = System.currentTimeMillis();

        byte[] buffer = new byte[10240];

        try {
            BufferedReader in = new BufferedReader(new FileReader(filename));
            lineIn = in.readLine();

            while(lineIn != null) {
                Command comm = new Command(lineIn);

                // Construct data
                String data = comm.getEncoding();

                // Send data

                URL url = new URL("http://" + host + ":46202/stockserv/stockserv");
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("POST");
                conn.setInstanceFollowRedirects(false);
                conn.setAllowUserInteraction(false);
                conn.setRequestProperty( "Content-type", "application/x-www-form-urlencoded" );
                conn.setDoOutput(true);
                conn.setDoInput(true);
                conn.setRequestProperty( "Content-length", Integer.toString(data.length()));
                if(sessions.containsKey(comm.getUsername())) {
                    conn.setRequestProperty("Cookie", (String) sessions.get(comm.getUsername()));
                } else {
		    //System.out.println("Sending without cookie: " + data);
		}
                OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
                debugLog.info("Command: " + data);
                wr.write(data);
                wr.flush();
                wr.close();

                // Get the response
                if(!sessions.containsKey(comm.getUsername())) {
                    // Look for our cookie (there are two now)
                    for (int i = 1; i < 10; ++i) {
                        String key = conn.getHeaderFieldKey(i);
                        if (key == null) {
                            break;
                        }
                        debugLog.info("Key: " + key);
                        if (key.equals("Set-Cookie")) {
                            String value = conn.getHeaderField(i);
                            if (value.startsWith("sessionid")) {
                                // Found it.
                                sessionID = value.substring(0, value.indexOf(";"));
                                System.out.println("SESSIONID: " + sessionID);
                                sessions.put(comm.getUsername(), sessionID);
                                break;
                            }
                        } else if (key.equals("Date")) {
                            // Cookie isn't there.
                            break;
                        }
                    }
                }
                //BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                //String line;
                //while ((line = rd.readLine()) != null) {
                //debugLog.debug(line);
                //}
                InputStream input = conn.getInputStream();
                int len;
                while ((len = input.read(buffer)) > 0) {
                    //
                }

                //rd.close();
                input.close();
                Main.countCommand();
                lineIn = in.readLine();
                if(timeToQuit >0 && System.currentTimeMillis() - startTime > (long) timeToQuit*1000) {
                    System.out.println(filename + ": Timed out");
                    break;
                }
            }

            in.close();
        } catch (IOException e) {
            debugLog.debug(filename + ": Could not open URL");
	    System.out.println("ERROR.  Could not open URL: " + e.getMessage());
            //e.printStackTrace();
            return;
        } catch (Exception e) {
            debugLog.debug(filename + ": Unknown Error - Stuff went wrong");
	    System.out.println("ERROR.  Generic error: " + e.getMessage());
            //e.printStackTrace();
            return;
        }

        /*Iterator i = commList.iterator();
        int prevCommand = 0;

        while(i.hasNext()) {

            //For testing and confirming of correctness.
            Command c = (Command) i.next();
            if(c.getName().equals("DUMPLOG")) {
                break;
            }

            String s = "[" + c.getCommandNumber() + "] " + c.getName() + ","
                    + c.getUsername();
            LinkedList l = c.getAttributes();
            Iterator iter = l.iterator();

            while(iter.hasNext()){
                s = s.concat("," + iter.next());
            }//endWhile

            if(prevCommand >= c.getCommandNumber()) {
                debugLog.debug(filename + ": Your out of Order!");
            }

            //System.out.println(s);
            prevCommand = c.getCommandNumber();
            //Send Post data to the WebServer.
        }//endWhile
         */
    }//endMethod
}//endClass
